//
//  SessionManager.m
//  DayByDay
//
//  Created by dllo on 16/5/29.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "SessionManager.h"

@interface SessionManager ()<NSURLSessionDownloadDelegate>

@property (nonatomic, strong)NSURLSession *session;
@property (nonatomic, strong)NSURLSessionDownloadTask *downLoadTask;
@property (nonatomic, strong)NSData *taskData;
@property (nonatomic, copy)NSString *urlStr;
@property (nonatomic, copy)NSString *pathStr;

@end

@implementation SessionManager

- (void)downLoadUrl:(NSString *)urlStr {
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *pathStr = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%f.data",[[NSDate date] timeIntervalSince1970]]];
    self.pathStr = pathStr;
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSURLSessionConfiguration *conf = [NSURLSessionConfiguration defaultSessionConfiguration];
    self.session = [NSURLSession sessionWithConfiguration:conf delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    self.downLoadTask = [self.session downloadTaskWithRequest:request];
    [self.downLoadTask resume];
}

- (void)pauseDownLoad {
    [self.downLoadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
        self.taskData = resumeData;
        
    }];
    //访问temp文件夹
//    NSString *tmpPath = NSTemporaryDirectory();
    
    //    NSLog(@"%@",tmpPath)
        [self.taskData writeToFile:_pathStr atomically:YES];
    self.downLoadTask = nil;
}

// 开始任务
- (void)resumeDownLoad {
    if (!self.taskData) {
        return;
    } else {
        self.downLoadTask = [self.session downloadTaskWithResumeData:self.taskData];
    }
    [self.downLoadTask resume];
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    // 计算进度
    self.progress = 1.0 * totalBytesWritten / totalBytesExpectedToWrite;
    NSLog(@"供下载了%f",self.progress);

    
    
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
        NSFileManager *manager = [NSFileManager defaultManager];
        //移动文件到自己的路径下®
        [manager moveItemAtPath:location.path toPath:self.pathStr error:nil];
    
}

@end
